package com.ssl.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ssl.mall.product.convert.CategoryConvert;
import com.ssl.mall.product.entity.Category;
import com.ssl.mall.product.entity.vo.CategoryVO;
import com.ssl.mall.product.mapper.CategoryMapper;
import com.ssl.mall.product.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品三级分类 服务实现类
 * </p>
 *
 * @author ssl
 * @since 2021-04-25
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    @Override
    public List<CategoryVO> allWithTree() {
        List<Category> all = baseMapper.selectList(new QueryWrapper<>());
        List<CategoryVO> vos = CategoryConvert.INSTANCE.entitys2VOs(all);

        List<CategoryVO> voList = vos.stream()
                .filter((category -> category.getParentCid().longValue() == 0))
                .map(vo -> {
                    vo.setChildrens(setChildrens(vo, vos));
                    return vo;
                })
                .sorted(Comparator.comparingInt(CategoryVO::getSort))
                .collect(Collectors.toList());
        return voList;
    }


    @Override
    public void updateCascade(Category category) {
        updateById(category);
        // TODO
    }

    @Override
    public void removeCatByIds(List<Long> catIds) {
        removeByIds(catIds);
    }

    private List<CategoryVO> setChildrens(CategoryVO root, List<CategoryVO> allVos) {

        List<CategoryVO> vos = allVos.stream()
                .filter((vo) -> vo.getParentCid().longValue() == root.getCatId())
                .map(vo -> {
                    vo.setChildrens(setChildrens(vo, allVos));
                    return vo;
                })
                .sorted(Comparator.comparingInt(CategoryVO::getSort))
                .collect(Collectors.toList());
        return vos;
    }
}
